import {$common} from './common';
import { reportError,Log } from './report' ;


const baseUrl = 'https://faceid.qq.com';
const backupUrl = 'https://faceid.qcloud.com';



/**
 * Request
 * @param {Object} [reTry] - 需要重试
 * @param {string} reTry.tryCount - 重试次数
 * @param {string} [reTry.retryDelay = 0] - 重试延迟执行时间，单位ms
 */
let request = function (wx_req, callback) {
  let { url, method = 'POST', data, reTry, header = { 'Content-Type': 'application/json' } } = wx_req;
  console.log(`requestPromise start:`, uni.faceidVerifySdkBaseUrl,url, data);
  const _callback = callback ? callback : (msg) => {
    return msg
  }
  const retryFun = (err) => {
    if (reTry && reTry.tryCount && reTry.tryCount > 0) {
      reTry.tryCount--;
      $common.setBaseUrl(backupUrl);
      setTimeout(() => {
        request(wx_req, callback);
      }, reTry.retryDelay || 0);
    } else {
      if (
        err.errMsg.indexOf('request:fail Unable to resolve host') >= 0 ||
        err.errMsg.indexOf('request:fail 似乎已断开与互联网的连接') >= 0
      ) {
        _callback({ ErrorCode: 101, ErrorMsg: '网络异常，请稍后重试' });
      } else if (err.errMsg === 'request:fail url not in domain list') {
        callback({
          ErrorCode: -104,
          ErrorMsg: '接口还未添加到服务器域名，请点击右上角三个点，打开调试模式再试'
        })
      } else {
        _callback({ ErrorCode: -107, ErrorMsg: 'request请求异常，请稍后重试' });
      }
      $common.setBaseUrl(baseUrl);
    }
  };
  try {
    uni.request({
      url: uni.faceidVerifySdkBaseUrl + url,
      method,
      data,
      header,
      success(res) {
        console.log(`request success:`, res);
        if (res.statusCode === 200 && res.data) {
          if (res.data.ErrorCode === 0 || res.data.code === 0) {
            _callback({ ErrorCode: 0, Data: res.data.Data || res.data.data });
          } else {
            // 当出现requestok，但 res.data === 504错误html文本时，前端需提示res.data
            _callback({
              ErrorCode: res.data.ErrorCode,
              ErrorMsg: res.data.ErrorMsg,
              Data: res.data.Data || res.data.data,
            });
          }
        } else {
          retryFun(res);
        }

      },
      fail(err) {
        console.log(`request error:`, err);
        retryFun(err);
        reportError(Log.requestFail, { url: `${uni.faceidVerifySdkBaseUrl}` + url, err })
      },
    });
  } catch (err) {
    console.log(`request error:`, err);
    _callback({ ErrorCode: -107, ErrorMsg: 'request请求异常，请稍后重试' });
    reportError(Log.requestCatch, { url: `${uni.faceidVerifySdkBaseUrl}` + url, err })
  }
};

export const $http = request ;